package com.tools.project.app;

import at.syntaxerror.json5.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Created by 2025/5/26
 *
 * @author 陈伟
 * @version V1.0
 * @description: 待补充...
 */
public class GitLabFileFetcher {

    public static void main(String[] args) {
        String projectId = "124";
        String branch = "dev";
        String filepath = "src/views/order/scheduling/出库调度列表动态表头接口初始化配置.json";
        String token = "CVzKfzX9eCqZsRyBby6t"; // 替换为你的 GitLab Personal Access Token

        try {
            String encodedString = URLEncoder.encode(filepath, StandardCharsets.UTF_8);
            String apiUrl = String.format(
                    "https://gitlab.facehand.cn/api/v4/projects/%s/repository/files/%s?ref=%s",
                    projectId, encodedString, branch
            );


            // 创建 HTTP 连接
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("PRIVATE-TOKEN", token);
            conn.setRequestMethod("GET");

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 输出文件内容
            System.out.println("文件内容:\n" + response.toString());
            JSONObject jsonObject = new JSONObject(response.toString());
            String content = jsonObject.get("content").toString();

            // 解码 Base64 字符串为字节数组
            byte[] decodedBytes = Base64.getDecoder().decode(content);

            // 将字节数组转换为字符串
            String decodedString = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);

            // 输出解码后的字符串
            System.out.println("Decoded String: " + decodedString);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
